const { createApp } = Vue;

createApp({
    data() {        return {
            form: {
                name: '',
                className: ''
            },
            classList: [
                { name: '运维1班' },
                { name: '运维2班' },
                { name: '运维3班' }
            ],
            errors: {},
            isSubmitting: false,
            uploadProgress: 0,
            successMessage: '',
            submittedStudents: [],
            // 摄像头相关
            showCamera: false,
            capturedImage: null,
            videoStream: null,
            canvas: null
        }
    },    mounted() {
        // 从本地存储加载已提交的学生数据
        const savedStudents = localStorage.getItem('submittedStudents');
        if (savedStudents) {
            this.submittedStudents = JSON.parse(savedStudents);
        }
        
        // 创建canvas元素用于拍照
        this.canvas = document.createElement('canvas');
    },
    methods: {        validateForm() {
            this.errors = {};
            let isValid = true;

            // 验证姓名
            if (!this.form.name.trim()) {
                this.errors.name = '请输入姓名';
                isValid = false;
            } else if (this.form.name.trim().length < 2) {
                this.errors.name = '姓名至少需要2个字符';
                isValid = false;
            } else if (this.form.name.trim().length > 20) {
                this.errors.name = '姓名不能超过20个字符';
                isValid = false;
            }            // 验证班级
            if (!this.form.className) {
                this.errors.class = '请选择班级';
                isValid = false;
            }

            // 验证照片
            if (!this.capturedImage) {
                this.errors.photo = '请拍摄人脸照片';
                isValid = false;
            }

            return isValid;
        },        async submitForm() {
            if (!this.validateForm()) {
                return;
            }

            this.isSubmitting = true;
            this.uploadProgress = 0;
            this.successMessage = '';

            try {
                // 将base64图片转换为Blob
                const imageBlob = await this.dataURLtoBlob(this.capturedImage);
                
                // 创建FormData
                const formdata = new FormData();
                formdata.append("file", imageBlob, `${this.form.name}_face.jpg`);                // 构建API URL - 使用配置文件中的地址
                const apiUrl = `${getApiUrl('studentRegister')}?name=${encodeURIComponent(this.form.name.trim())}&className=${this.form.className}`;                // 配置请求选项
                const requestOptions = {
                    method: 'POST',
                    body: formdata,
                    redirect: 'follow',
                    mode: 'cors', // 明确指定CORS模式
                    headers: {
                        // 不要设置Content-Type，让浏览器自动设置multipart/form-data
                    }
                };

                console.log('发送请求到:', apiUrl);
                console.log('请求选项:', requestOptions);

                // 模拟上传进度
                const progressInterval = setInterval(() => {
                    if (this.uploadProgress < 90) {
                        this.uploadProgress += 10;
                    }
                }, 200);// 发送请求
                const response = await fetch(apiUrl, requestOptions);
                
                clearInterval(progressInterval);
                this.uploadProgress = 100;

                if (response.ok) {
                    const result = await response.text();
                    console.log('API响应:', result);                    // 创建学生记录
                    const student = {
                        name: this.form.name.trim(),
                        className: this.form.className,
                        time: this.formatDateTime(new Date()),
                        status: '已登记'
                    };

                    // 添加到已提交列表
                    this.submittedStudents.unshift(student);

                    // 保存到本地存储
                    localStorage.setItem('submittedStudents', JSON.stringify(this.submittedStudents));

                    // 显示成功消息
                    this.successMessage = `学生 ${student.name} (${student.className}) 人脸信息已成功登记！`;

                    // 重置表单
                    this.resetForm();

                    // 5秒后清除成功消息
                    setTimeout(() => {
                        this.successMessage = '';
                    }, 5000);

                } else {
                    throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
                }            } catch (error) {
                console.error('提交失败:', error);
                
                // 检查是否是CORS错误
                let errorMessage = error.message;
                if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
                    errorMessage = 'CORS错误：无法连接到后端服务器。这可能是因为:\n' +
                                 '1. 后端服务器未配置CORS允许跨域请求\n' +
                                 '2. 后端服务器未启动 (http://localhost:8080)\n' +
                                 '3. 网络连接问题\n\n' +
                                 '解决方案：\n' +
                                 '- 联系后端开发人员配置CORS\n' +
                                 '- 或使用start-dev.bat启动开发环境';
                }
                
                this.errors.submit = errorMessage;
            } finally {
                this.isSubmitting = false;
                this.uploadProgress = 0;
            }
        },

        // 摄像头相关方法
        async startCamera() {
            try {
                this.videoStream = await navigator.mediaDevices.getUserMedia({ 
                    video: { 
                        facingMode: 'user',
                        width: { ideal: 640 },
                        height: { ideal: 480 }
                    } 
                });
                this.showCamera = true;
                
                // 等待DOM更新
                await this.$nextTick();
                
                if (this.$refs.video) {
                    this.$refs.video.srcObject = this.videoStream;
                }
            } catch (error) {
                console.error('无法访问摄像头:', error);
                this.errors.photo = '无法访问摄像头，请检查权限设置';
            }
        },

        capturePhoto() {
            if (!this.$refs.video || !this.videoStream) {
                return;
            }

            const video = this.$refs.video;
            this.canvas.width = video.videoWidth;
            this.canvas.height = video.videoHeight;
            
            const context = this.canvas.getContext('2d');
            context.drawImage(video, 0, 0);
            
            // 转换为base64格式
            this.capturedImage = this.canvas.toDataURL('image/jpeg', 0.8);
            
            // 停止摄像头
            this.stopCamera();
        },

        stopCamera() {
            if (this.videoStream) {
                this.videoStream.getTracks().forEach(track => track.stop());
                this.videoStream = null;
            }
            this.showCamera = false;
        },

        retakePhoto() {
            this.capturedImage = null;
            this.startCamera();
        },

        clearPhoto() {
            this.capturedImage = null;
            if (this.errors.photo) {
                delete this.errors.photo;
            }
        },        resetForm() {
            this.form = {
                name: '',
                className: ''
            };
            this.capturedImage = null;
            this.errors = {};
        },        // 工具方法
        async dataURLtoBlob(dataURL) {
            const response = await fetch(dataURL);
            return response.blob();
        },

        formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        },

        clearAllData() {
            if (confirm('确定要清空所有登记数据吗？此操作不可恢复！')) {
                this.submittedStudents = [];
                localStorage.removeItem('submittedStudents');
                this.successMessage = '所有数据已清空';
                setTimeout(() => {
                    this.successMessage = '';
                }, 2000);
            }
        }
    },    watch: {
        // 监听表单变化，清除对应的错误信息
        'form.name'() {
            if (this.errors.name) {
                delete this.errors.name;
            }
        },
        'form.className'() {
            if (this.errors.class) {
                delete this.errors.class;
            }
        },
        'capturedImage'() {
            if (this.errors.photo) {
                delete this.errors.photo;
            }
        }
    },

    beforeUnmount() {
        // 组件销毁前停止摄像头
        this.stopCamera();
    }
}).mount('#app');
